//
//  AppDelegate.m
//  CallPolice
//
//  Created by mac on 2017/12/5.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewControler.h"
#import "ViewController.h"
#import "WXDataBase.h"
#import "MessageModel.h"
#import "ConfigureHeader.h"
#import <JPush/JPUSHService.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import <AdSupport/AdSupport.h>
#import <AVFoundation/AVFoundation.h>
@interface AppDelegate ()<JPUSHRegisterDelegate,UNUserNotificationCenterDelegate>
@property (nonatomic,strong) NSDateFormatter *formatter;

@end

@implementation AppDelegate
- (NSDateFormatter *)formatter{
    if (!_formatter) {
        _formatter =[[NSDateFormatter alloc]init];
        [_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    return _formatter;
}
- (void)creatDB{
    WXDataBase *DB = [WXDataBase ShareDataBaseInstance];
    [DB creatTableModelIndexofName:TABLE_NAME andClass:MessageModel.class];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [self creatDB];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    NSArray *array =[[WXDataBase ShareDataBaseInstance] getAllObjectsOfClass:MessageModel.class fromTable:TABLE_NAME];

    if (array.count>200) {
        [[WXDataBase ShareDataBaseInstance]deleteObjectsFromTable:TABLE_NAME limit:100 offset:0];
    }
    NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
//    NSLog(@"%@",remoteNotification);
    if (remoteNotification) {
        MessageModel *model =[[MessageModel alloc]init];
        model.localID = [NSDate date];
        NSDate *date =[NSDate dateWithTimeIntervalSince1970:[[remoteNotification valueForKeyPath:@"date"] integerValue]];
        model.createTime = [self.formatter stringFromDate:date];
        model.content = [remoteNotification valueForKeyPath:@"content"];
        [self addMessage:model];
    }
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    
    if ([[UIDevice currentDevice].systemVersion floatValue]>= 8.0) {
        //可以添加自定义categories
        if ([[UIDevice currentDevice].systemVersion floatValue]>= 10.0) {
            if (@available(iOS 10.0, *)) {
                NSSet<UNNotificationCategory *> *categories;
                entity.categories = categories;
                
            } else {
                // Fallback on earlier versions
            }
        }
        else {
            NSSet<UIUserNotificationCategory *> *categories;
            entity.categories = categories;
        }
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:@"1d54cd951a050d082c36c7aa"
                          channel:@""
                 apsForProduction:NO
            advertisingIdentifier:advertisingId];
      self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
     LoginViewControler *loginVc = [[LoginViewControler alloc]initWithNibName:NSStringFromClass([LoginViewControler class]) bundle:nil];
    //2.1.9版本新增获取registration id block接口。
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
 
    [[UINavigationBar appearance]setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,[UIFont fontWithName:@"MicrosoftYaHei" size:18],NSFontAttributeName, nil]];
//    [UINavigationBar appearance].translucent = NO;
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:17/255.0 green:129/255.0 blue:209/255.0 alpha:1]];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    UIStoryboard *board =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ViewController *vc = [board instantiateInitialViewController];
     UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
    self.window.rootViewController = loginVc;
    [self.window makeKeyAndVisible];
    return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {

    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS7及以上系统，收到通知:%@", userInfo);
    MessageModel *model =[[MessageModel alloc]init];
    model.localID = [NSDate date];
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:[[userInfo valueForKeyPath:@"date"] integerValue]];
    model.createTime = [self.formatter stringFromDate:date];
    model.content = [userInfo valueForKeyPath:@"content"];
    [self addMessage:model];
    [[NSNotificationCenter defaultCenter]postNotificationName:PUSH_REMOTE object:nil userInfo:userInfo];

    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {

    }

    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];

    
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        UNNotificationRequest *request = notification.request;
        UNNotificationContent *content = request.content; // 收到推送的消息内容
        NSNumber *badge = content.badge;  // 推送消息的角标
        NSString *body = content.body;    // 推送消息体
        UNNotificationSound *sound = content.sound;  // 推送消息的声音
        NSString *subtitle = content.subtitle;  // 推送消息的副标题
        NSString *title = content.title;
        // 推送消息的标题
        
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
//            NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
//            [self.alertView setMessage:[userInfo valueForKeyPath:@"aps.alert"]];
//            [self.alertView show];
            //        [rootViewController addNotificationCount];
        }
        else {
            // 判断为本地通知
            NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
            
          
        }
        completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    } else {
        
        // Fallback on earlier versions
    } // 收到推送的请求
    
    
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        UNNotificationRequest *request = response.notification.request;
        // 收到推送的请求
        UNNotificationContent *content = request.content; // 收到推送的消息内容
        NSNumber *badge = content.badge;  // 推送消息的角标
        NSString *body = content.body;    // 推送消息体
        UNNotificationSound *sound = content.sound;  // 推送消息的声音
        NSString *subtitle = content.subtitle;  // 推送消息的副标题
        NSString *title = content.title;  // 推送消息的标题
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
//            NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
            //        [[UIApplication sharedApplication].keyWindow.rootViewController addNotificationCount];
            NSLog(@"iOS10 收到远程通知:%@",userInfo);
            MessageModel *model =[[MessageModel alloc]init];
            model.localID = [NSDate date];
            NSDate *date =[NSDate dateWithTimeIntervalSince1970:[[userInfo valueForKeyPath:@"date"] integerValue]];
            model.createTime = [self.formatter stringFromDate:date];
            model.content = [userInfo valueForKeyPath:@"content"];
            [self addMessage:model];
              [[NSNotificationCenter defaultCenter]postNotificationName:PUSH_REMOTE object:nil userInfo:userInfo];
        }
        else {
            // 判断为本地通知
            NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
        }
        
        // 系统要求执行这个方法
        completionHandler();
        [JPUSHService handleRemoteNotification:userInfo];
        
        
    } else {
        NSLog(@"---------");
        // Fallback on earlier versions
    }
}
- (void) addMessage:(MessageModel*)model{
    
    [[WXDataBase ShareDataBaseInstance] insertAModelWithModelName:model intoTableName:TABLE_NAME];
    NSArray *messages=[[WXDataBase ShareDataBaseInstance] getAllObjectsOfClass:[MessageModel class] fromTable:TABLE_NAME];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    
}
#endif

@end
